using UnityEditor;
using UnityEngine;
using System.Linq;
using System.Collections.Generic;
using System;
using UnityEngine.Rendering;

public static class CommonEffectGUI
{
    // 混合模式类型枚举
    public enum BlendMode
    {
        Alpha,
        Premultiply,
        Add,
        Multiply
    }

    // 折叠框状态
    private enum FoldoutState
    {
        Collapsed,
        Expanded,
        Hovered
    }

    // GUI样式定义
    private static GUIStyle activeButtonStyle;
    private static GUIStyle inactiveButtonStyle;
    private static GUIStyle textShadowStyle;
    private static GUIStyle sectionBackgroundStyle;
    private static GUIStyle foldoutHeaderStyle;
    private static GUIStyle foldoutContentStyle;
    private static GUIStyle infoBarStyle;
    private static GUIStyle presetButtonStyle;  // 预设按钮样式
    private static GUIStyle redButtonStyle;     // 红色按钮样式

    // 固定高度常量定义
    private const float HeaderHeight = 30f;
    private const float ButtonHeight = 20f;
    private const float ButtonHeadHeight = 27f;
    private const float SectionSpacing = 4f;
    private const float ContentSpacing = 8f;
    private const float LabelWidth = 80f;
    private const float InfoBarHeight = 20f;
    private const float PresetButtonWidth = 30f;  // 预设按钮宽度
    private const float PresetHeight = 18f;  // 预设按钮宽度
    private const float RefreshButtonWidth = 100f;  // 刷新按钮宽度

    // 缓存的顶部装饰条和背景样式
    private static readonly Dictionary<FoldoutState, GUIStyle> topBarStyles = new Dictionary<FoldoutState, GUIStyle>();
    private static readonly Dictionary<FoldoutState, GUIStyle> backgroundStyles = new Dictionary<FoldoutState, GUIStyle>();

    // 折叠状态记忆
    private static readonly Dictionary<int, bool> foldoutStates = new Dictionary<int, bool>();
    private static int currentHoveredInstanceId = -1;
    private static bool isMouseOverGui = false;
    private static Rect currentGuiRect;

    // 预设材质球路径（可以在Editor中设置）
    private static string preset1Path = "Assets/LaskyUnityPack/LaskyShaderPack/Common/Mat/Demo/DemoUber_1.mat";
    private static string preset2Path = "Assets/LaskyUnityPack/LaskyShaderPack/Common/Mat/Demo/DemoUber_2.mat";
    private static string preset3Path = "Assets/LaskyUnityPack/LaskyShaderPack/Common/Mat/Demo/DemoUber_3.mat";

    // 静态构造函数初始化样式
    static CommonEffectGUI()
    {
        InitStyles();
    }

    // 初始化所有样式
    private static void InitStyles()
    {
        if (sectionBackgroundStyle != null) return;

        // 区域背景样式
        sectionBackgroundStyle = new GUIStyle
        {
            normal = { background = MakeTex(2, 2, new Color(0.1f, 0.1f, 0.1f, 0.9f)) },
            padding = new RectOffset(8, 8, 8, 8)
        };

        // 激活状态按钮样式
        activeButtonStyle = new GUIStyle(GUI.skin.button)
        {
            normal = { background = MakeTex(2, 2, new Color(0.2f, 0.3f, 0.4f, 1f)) },
            hover = { background = MakeTex(2, 2, new Color(0.3f, 0.6f, 0.8f, 1f)) },
            active = { background = MakeTex(2, 2, new Color(0.1f, 0.3f, 0.5f, 1f)) },
            alignment = TextAnchor.MiddleCenter,
            fontStyle = FontStyle.Normal,
            fixedHeight = ButtonHeight
        };

        // 未激活状态按钮样式
        inactiveButtonStyle = new GUIStyle(GUI.skin.button)
        {
            normal = { background = MakeTex(2, 2, new Color(0.15f, 0.15f, 0.15f, 1f)) },
            hover = { background = MakeTex(2, 2, new Color(0.35f, 0.35f, 0.35f, 1f)) },
            active = { background = MakeTex(2, 2, new Color(0.15f, 0.15f, 0.15f, 1f)) },
            alignment = TextAnchor.MiddleCenter,
            fontStyle = FontStyle.Normal,
            fixedHeight = ButtonHeight
        };

        // 红色按钮样式
        redButtonStyle = new GUIStyle(GUI.skin.button)
        {
            normal = { background = MakeTex(2, 2, new Color(0.6f, 0.2f, 0.2f, 1f)) },
            hover = { background = MakeTex(2, 2, new Color(0.8f, 0.3f, 0.3f, 1f)) },
            active = { background = MakeTex(2, 2, new Color(0.5f, 0.1f, 0.1f, 1f)) },
            alignment = TextAnchor.MiddleCenter,
            fontStyle = FontStyle.Normal,
            fixedHeight = ButtonHeight
        };

        // 文字底纹样式
        textShadowStyle = new GUIStyle
        {
            normal = { textColor = Color.white },
            fontSize = 12,
            fontStyle = FontStyle.Normal,
            fixedWidth = LabelWidth,
            fixedHeight = ButtonHeadHeight,
            alignment = TextAnchor.MiddleLeft,
            stretchHeight = false
        };

        // 折叠框标题样式
        foldoutHeaderStyle = new GUIStyle
        {
            normal = { textColor = Color.white },
            fontSize = 14,
            fontStyle = FontStyle.Bold,
            alignment = TextAnchor.MiddleCenter,
            padding = new RectOffset(10, 10, 8, 8),
            fixedHeight = HeaderHeight
        };

        // 折叠框内容样式
        foldoutContentStyle = new GUIStyle
        {
            padding = new RectOffset(8, 8, 8, 8)
        };

        // 信息栏样式
        infoBarStyle = new GUIStyle
        {
            normal = { textColor = new Color(0.7f, 0.7f, 0.7f) },
            fontSize = 10,
            alignment = TextAnchor.MiddleLeft,
            fixedHeight = InfoBarHeight
        };

        // 预设按钮样式
        presetButtonStyle = new GUIStyle(GUI.skin.button)
        {
            normal = { background = MakeTex(2, 2, new Color(0.15f, 0.15f, 0.15f, 1f)) },
            hover = { background = MakeTex(2, 2, new Color(0.3f, 0.3f, 0.3f, 1f)) },
            active = { background = MakeTex(2, 2, new Color(0.1f, 0.2f, 0.3f, 1f)) },
            alignment = TextAnchor.MiddleCenter,
            fontSize = 9,
            fixedHeight = PresetHeight - 2,
            fixedWidth = PresetButtonWidth
        };

        // 预缓存状态样式
        CacheStateStyles();
    }

    // 缓存状态相关样式
    private static void CacheStateStyles()
    {
        topBarStyles[FoldoutState.Hovered] = CreateStateStyle(new Color(0.4f, 0.4f, 0.4f));
        topBarStyles[FoldoutState.Expanded] = CreateStateStyle(new Color(0.6f, 0.6f, 0.6f));
        topBarStyles[FoldoutState.Collapsed] = CreateStateStyle(new Color(0.4f, 0.4f, 0.4f));

        backgroundStyles[FoldoutState.Hovered] = CreateStateStyle(new Color(0.15f, 0.15f, 0.15f, 0.95f));
        backgroundStyles[FoldoutState.Expanded] = CreateStateStyle(new Color(0.1f, 0.1f, 0.1f, 0.95f));
        backgroundStyles[FoldoutState.Collapsed] = CreateStateStyle(new Color(0.08f, 0.08f, 0.08f, 0.95f));
    }

    // 创建状态样式的辅助方法
    private static GUIStyle CreateStateStyle(Color color)
    {
        return new GUIStyle
        {
            normal = { background = MakeTex(2, 2, color) }
        };
    }

    // 缓存的1x1像素纹理
    private static Texture2D whitePixel;
    // 修改MakeTex方法，确保纹理正确创建和缓存
    private static Texture2D MakeTex(int width, int height, Color col)
    {
        // 使用更稳定的纹理创建方式
        Texture2D result = new Texture2D(width, height, TextureFormat.ARGB32, false)
        {
            // 设置合适的纹理模式防止拉伸失真
            wrapMode = TextureWrapMode.Clamp,
            filterMode = FilterMode.Point,
            // 标记为不保存到磁盘且不被GC自动回收
            hideFlags = HideFlags.DontSave | HideFlags.NotEditable
        };

        Color[] pix = new Color[width * height];
        for (int i = 0; i < pix.Length; i++)
            pix[i] = col;

        result.SetPixels(pix);
        result.Apply(false, true); // 第二个参数设为true强制立即上传到GPU

        return result;
    }


    // 单材质绘制方法
    public static void Draw(Material material, MaterialEditor materialEditor)
    {
        if (material == null) return;
        Draw(new[] { material }, materialEditor);
    }

    // 多材质绘制方法（主入口）
    public static void Draw(Material[] materials, MaterialEditor materialEditor)
    {
        InitStyles();

        var validMaterials = materials?.Where(m => m != null).ToArray();
        if (validMaterials == null || validMaterials.Length == 0 || materialEditor == null) return;

        Rect startRect = GUILayoutUtility.GetRect(0, 0);
        if (currentGuiRect.x != startRect.x || currentGuiRect.y != startRect.y)
        {
            currentGuiRect.x = startRect.x;
            currentGuiRect.y = startRect.y;
        }

        HandleMouseEvent();

        int mainMaterialId = validMaterials[0].GetInstanceID();
        if (!foldoutStates.ContainsKey(mainMaterialId))
        {
            foldoutStates[mainMaterialId] = EditorPrefs.GetBool($"CommonEffectGUI_Foldout_{mainMaterialId}", true);
        }

        DrawFoldout(validMaterials, materialEditor, mainMaterialId);

        Rect endRect = GUILayoutUtility.GetRect(0, 0);
        if (currentGuiRect.width != endRect.x - currentGuiRect.x || currentGuiRect.height != endRect.y - currentGuiRect.y)
        {
            currentGuiRect.width = endRect.x - currentGuiRect.x;
            currentGuiRect.height = endRect.y - currentGuiRect.y;
        }
    }

    // 鼠标事件处理
    private static void HandleMouseEvent()
    {
        Event currentEvent = Event.current;
        if (currentEvent == null) return;

        switch (currentEvent.type)
        {
            case EventType.MouseMove:
            case EventType.MouseDown:
            case EventType.MouseUp:
                isMouseOverGui = currentGuiRect.Contains(currentEvent.mousePosition);
                break;
            case EventType.MouseEnterWindow:
                isMouseOverGui = true;
                break;
            case EventType.MouseLeaveWindow:
                isMouseOverGui = false;
                break;
        }
    }

    // 绘制自定义折叠框
    private static void DrawFoldout(Material[] validMaterials, MaterialEditor materialEditor, int instanceId)
    {
        bool isExpanded = foldoutStates[instanceId];
        Rect headerRect = GUILayoutUtility.GetRect(0, HeaderHeight + InfoBarHeight, foldoutHeaderStyle);
        bool isHovered = headerRect.Contains(Event.current.mousePosition);

        if (isHovered)
        {
            if (currentHoveredInstanceId != instanceId)
            {
                currentHoveredInstanceId = instanceId;
                isMouseOverGui = true;
            }
        }
        else if (currentHoveredInstanceId == instanceId && Event.current.type == EventType.Repaint)
        {
            currentHoveredInstanceId = -1;
        }

        FoldoutState state = isHovered ? FoldoutState.Hovered :
                           isExpanded ? FoldoutState.Expanded : FoldoutState.Collapsed;

        GUI.Box(new Rect(headerRect.x, headerRect.y, headerRect.width, 8), "", topBarStyles[state]);
        GUI.Box(new Rect(headerRect.x, headerRect.y + 4, headerRect.width, headerRect.height), "", backgroundStyles[state]);

        // 标题绘制（留出刷新按钮空间）
        GUI.Label(new Rect(headerRect.x, headerRect.y + 5, headerRect.width - 30 , headerRect.height),
                 "特效通用材质", foldoutHeaderStyle);
        
        // 检查_BUILTIN_SURFACE_TYPE_TRANSPARENT关键字是否存在
        bool hasTransparentKeyword = validMaterials.All(mat => mat.IsKeywordEnabled("_BUILTIN_SURFACE_TYPE_TRANSPARENT"));
        
        // 绘制刷新按钮，根据关键字状态改变文本和样式
        string refreshButtonText = hasTransparentKeyword ? "刷新状态" : "请点击刷新";
        GUIStyle refreshButtonStyle = hasTransparentKeyword ? inactiveButtonStyle : redButtonStyle;
        
        Rect refreshBtnRect = new Rect(
            headerRect.x + headerRect.width - RefreshButtonWidth - 10,
            headerRect.y + 10,
            RefreshButtonWidth,
            HeaderHeight - 10
        );
        if (GUI.Button(refreshBtnRect, refreshButtonText, refreshButtonStyle))
        {
            RefreshMaterialStates(validMaterials);
        }
        
        // 绘制信息栏和预设按钮
        DrawInfoBarWithPresets(headerRect, validMaterials);
        
        GUILayout.Space(SectionSpacing);

        // 处理点击事件（排除刷新按钮区域）
        if (Event.current.type == EventType.MouseDown && headerRect.Contains(Event.current.mousePosition) && 
            !refreshBtnRect.Contains(Event.current.mousePosition))
        {
            foldoutStates[instanceId] = !isExpanded;
            EditorPrefs.SetBool($"CommonEffectGUI_Foldout_{instanceId}", foldoutStates[instanceId]);
            Event.current.Use();
        }

        // 绘制折叠内容
        if (isExpanded)
        {
            GUILayout.BeginVertical(sectionBackgroundStyle);
            GUILayout.Space(ContentSpacing);
            DrawSection(() => DrawBlendModeControls(validMaterials), "混合模式");
            DrawSection(() => DrawCullControls(validMaterials), "剔除模式");
            DrawSection(() => DrawZWriteControls(validMaterials), "深度写入");
            DrawSection(() => DrawInstancingAndGIControls(validMaterials), "GPU实例化");
            DrawSection(() => DrawRenderQueueControl(validMaterials), "渲染队列");

            GUILayout.Space(ContentSpacing);
            GUILayout.EndVertical();
        }
    }

    // 绘制信息栏和预设按钮
    private static void DrawInfoBarWithPresets(Rect headerRect, Material[] materials)
    {
        // 计算信息栏位置和宽度（留出预设按钮的空间）
        float infoBarWidth = headerRect.width - (PresetButtonWidth * 3 + 15); // 3个按钮 + 间距
        Rect infoBarRect = new Rect(
            headerRect.x + 10, 
            headerRect.y + HeaderHeight + 2, 
            infoBarWidth, 
            InfoBarHeight
        );

        // 绘制信息文本
        string renderPipeline = GetRenderPipeline();
        string shaderName = materials[0].shader != null ? materials[0].shader.name : "Unknown Shader";
        string currentTime = DateTime.Now.ToString("HH:mm:ss");
        string infoText = $"渲染管线: {renderPipeline} | Shader: {shaderName} | 时间: {currentTime}";
        GUI.Label(infoBarRect, infoText, infoBarStyle);

        // 绘制预设按钮
        DrawPresetButtons(headerRect, materials);
    }

    // 绘制预设按钮
    private static void DrawPresetButtons(Rect headerRect, Material[] materials)
    {
        // 计算第一个按钮的X位置（右对齐）
        float firstButtonX = headerRect.x + headerRect.width - (PresetButtonWidth * 3 + 10) - 10;
        
        // 预设1按钮
        Rect preset1Rect = new Rect(
            firstButtonX,
            headerRect.y + HeaderHeight + 5,
            PresetButtonWidth,
            PresetHeight 
        );
        if (GUI.Button(preset1Rect, "1", presetButtonStyle))
        {
            ApplyPreset(materials, preset1Path);
        }
        
        // 预设2按钮
        Rect preset2Rect = new Rect(
            firstButtonX + PresetButtonWidth + 5,
            headerRect.y + HeaderHeight + 5,
            PresetButtonWidth,
            PresetHeight 
        );
        if (GUI.Button(preset2Rect, "2", presetButtonStyle))
        {
            ApplyPreset(materials, preset2Path);
        }
        
        // 预设3按钮
        Rect preset3Rect = new Rect(
            firstButtonX + (PresetButtonWidth + 5) * 2,
            headerRect.y + HeaderHeight + 5,
            PresetButtonWidth,
            PresetHeight 
        );
        if (GUI.Button(preset3Rect, "3", presetButtonStyle))
        {
            ApplyPreset(materials, preset3Path);
        }
    }

    // 应用预设材质
    private static void ApplyPreset(Material[] targetMaterials, string presetPath)
    {
        // 从Asset数据库加载预设材质
        Material presetMaterial = AssetDatabase.LoadAssetAtPath<Material>(presetPath);
        
        if (presetMaterial == null)
        {
            Debug.LogWarning($"找不到预设材质: {presetPath}，请检查路径是否正确");
            return;
        }

        // 将预设材质的属性应用到目标材质
        foreach (var targetMat in targetMaterials)
        {
            Undo.RecordObject(targetMat, $"应用预设: {System.IO.Path.GetFileNameWithoutExtension(presetPath)}");
            
            // 复制关键属性
            CopyMaterialProperty(targetMat, presetMaterial, "_Blend");
            CopyMaterialProperty(targetMat, presetMaterial, "_SrcBlend");
            CopyMaterialProperty(targetMat, presetMaterial, "_DstBlend");
            CopyMaterialProperty(targetMat, presetMaterial, "_Cull");
            CopyMaterialProperty(targetMat, presetMaterial, "_ZWrite");
            CopyMaterialProperty(targetMat, presetMaterial, "_ZWriteControl");
            CopyMaterialProperty(targetMat, presetMaterial, "_CustomRenderQueue");
            
            // 复制实例化设置
            targetMat.enableInstancing = presetMaterial.enableInstancing;
            CopyMaterialProperty(targetMat, presetMaterial, "_EnableInstancingVariants");
            
            EditorUtility.SetDirty(targetMat);
        }
    }
    
    // 复制材质属性的辅助方法
    private static void CopyMaterialProperty(Material target, Material source, string propertyName)
    {
        if (source.HasProperty(propertyName) && target.HasProperty(propertyName))
        {
            // 尝试作为浮点型或范围型属性
            try
            {
                float value = source.GetFloat(propertyName);
                target.SetFloat(propertyName, value);
                return;
            }
            catch { }

            // 尝试作为整型属性
            try
            {
                int value = source.GetInt(propertyName);
                target.SetInt(propertyName, value);
                return;
            }
            catch { }

            // 尝试作为颜色属性
            try
            {
                Color color = source.GetColor(propertyName);
                target.SetColor(propertyName, color);
                return;
            }
            catch { }

            // 尝试作为向量属性
            try
            {
                Vector4 vector = source.GetVector(propertyName);
                target.SetVector(propertyName, vector);
                return;
            }
            catch { }
        }
    }

    // 获取当前渲染管线
    private static string GetRenderPipeline()
    {
        if (GraphicsSettings.defaultRenderPipeline != null)
        {
            string rpName = GraphicsSettings.defaultRenderPipeline.GetType().Name;
            if (rpName.Contains("UniversalRenderPipelineAsset"))
                return "URP";
            if (rpName.Contains("HDRenderPipelineAsset"))
                return "HDRP";
            return rpName;
        }
        return "Built-in";
    }

    // 绘制带标题的区域
    private static void DrawSection(System.Action content, string title)
    {
        GUILayout.BeginHorizontal();
        GUILayout.Space(ContentSpacing);
        GUILayout.Label(title, textShadowStyle);
        
        GUILayout.BeginVertical();
        GUILayout.Space(SectionSpacing);
        content.Invoke();
        GUILayout.Space(SectionSpacing);
        GUILayout.EndVertical();
        
        GUILayout.Space(ContentSpacing);
        GUILayout.EndHorizontal();
        GUILayout.Space(SectionSpacing);
    }

    // 自定义按钮绘制
    private static bool DrawCustomButton(string text, bool isActive, params GUILayoutOption[] options)
    {
        GUIStyle style = isActive ? activeButtonStyle : inactiveButtonStyle;
        Rect rect = GUILayoutUtility.GetRect(new GUIContent(text), style, options);
        bool clicked = GUI.Button(rect, GUIContent.none, style);

        style.normal.textColor = Color.white;
        style.hover.textColor = Color.white;
        style.active.textColor = Color.white;
        GUI.Label(rect, text, style);

        if (rect.Contains(Event.current.mousePosition))
        {
            isMouseOverGui = true;
        }
        
        return clicked;
    }

    // 混合模式控制
    private static void DrawBlendModeControls(Material[] materials)
    {
        GUILayout.BeginHorizontal();
        
        int? commonBlend = null;
        foreach (var mat in materials)
        {
            int blend = mat.GetInt("_Blend");
            if (commonBlend == null) 
                commonBlend = blend;
            else if (commonBlend != blend) 
            { 
                commonBlend = -1; 
                break; 
            }
        }

        if (DrawCustomButton("Alpha", commonBlend == 0, GUILayout.Height(ButtonHeight)))
            SetBlendMode(materials, 5, 10, 0);
        
        if (DrawCustomButton("Premultiply", commonBlend == 1, GUILayout.Height(ButtonHeight)))
            SetBlendMode(materials, 1, 10, 1);
        
        if (DrawCustomButton("Add", commonBlend == 2, GUILayout.Height(ButtonHeight)))
            SetBlendMode(materials, 5, 1, 2);
        
        if (DrawCustomButton("Multiply", commonBlend == 3, GUILayout.Height(ButtonHeight)))
            SetBlendMode(materials, 2, 0, 3);
        
        GUILayout.EndHorizontal();
    }

    private static void SyncRenderStates(Material mat)
    {
        if (mat == null) return; // 防止空引用错误

        // 同步内置渲染状态参数（根据diff提取的关键配置）
        mat.SetInt("_BUILTIN_Surface", 1);
        mat.SetInt("_BUILTIN_SrcBlend", 5);
        mat.SetInt("_BUILTIN_DstBlend", 10);
        mat.SetInt("_BUILTIN_ZWrite", 0);
        mat.SetInt("_BUILTIN_CullMode", 0);
        mat.SetInt("_BUILTIN_ZTest", 4);
        mat.SetInt("_BUILTIN_QueueControl", 1);
        
        // 同步常规渲染参数
        mat.SetInt("_ZWrite", 0);
        mat.SetInt("_Cull", 0);
        mat.SetInt("_CullMode", 0);
        mat.SetInt("_CullModeForward", 0);
        mat.SetInt("_SurfaceType", 1);
        mat.SetInt("_CastShadows", 0);
        mat.SetInt("_Blend", 0);
                // 新增的属性设置
        mat.SetInt("_AlphaDstBlend", 10);
        mat.SetInt("_DstBlend2", 10);
        mat.SetInt("_SrcBlend", 1);
        mat.SetInt("_StencilRefDepth", 1);
        mat.SetInt("_StencilRefMV", 33);
        mat.SetInt("_StencilWriteMaskMV", 43);
        mat.SetInt("_ZTestDepthEqualForOpaque", 4);
        
        // 同步渲染队列
        mat.renderQueue = 3000;
        
        // 同步内置关键字
        mat.EnableKeyword("_BUILTIN_SURFACE_TYPE_TRANSPARENT");
        mat.EnableKeyword("_CHROMEMODE_OFF");
        mat.EnableKeyword("_DECALMODE_OFF");
        mat.EnableKeyword("_DISTORTMODE_OFF");
        mat.EnableKeyword("_MASKMODE_OFF");
        mat.EnableKeyword("_ROTATETOGGLE_ON");
        mat.EnableKeyword("_UVMODE_UV");
        
        // 禁用无效关键字
        mat.DisableKeyword("_disable_SSR_TRANSPARENT");
        mat.DisableKeyword("_NORMALMAP_TANGENT_SPACE");
    }
    
    private static void RefreshMaterialStates(Material[] materials)
    {
        foreach (var mat in materials)
        {
            Undo.RecordObject(mat, "Refresh Material States");

            // 同步核心渲染状态
            SyncRenderStates(mat);

            // 同步标签
            mat.SetOverrideTag("MotionVector", "User");
            mat.SetOverrideTag("RenderType", "Transparent");

            // 同步关键字
            mat.EnableKeyword("_SURFACE_TYPE_TRANSPARENT");
            mat.EnableKeyword("_ENABLE_FOG_ON_TRANSPARENT");
            // 关闭雾效关键字
            mat.DisableKeyword("_ENABLE_FOG_ON_TRANSPARENT");
            // 强制刷新并保存
            EditorUtility.SetDirty(mat);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh(); 
        }
    }
    
    // 批量设置混合模式
    private static void SetBlendMode(Material[] materials, int srcBlend, int dstBlend, int blend)
    {
        foreach (var mat in materials)
        {
            Undo.RecordObject(mat, "Change Blend Mode");
            mat.SetInt("_SrcBlend", srcBlend);
            mat.SetInt("_DstBlend", dstBlend);
            mat.SetInt("_Blend", blend);
            EditorUtility.SetDirty(mat);
        }
    }

    // 剔除模式控制
    private static void DrawCullControls(Material[] materials)
    {
        GUILayout.BeginHorizontal();
        
        int? commonCull = null;
        foreach (var mat in materials)
        {
            // 检查主要的_Cull属性作为参考
            int cull = mat.GetInt("_Cull");
            if (commonCull == null) 
                commonCull = cull;
            else if (commonCull != cull) 
            { 
                commonCull = -1; 
                break; 
            }
        }

        if (DrawCustomButton("双面渲染", commonCull == 0, GUILayout.Height(ButtonHeight)))
            SetCullMode(materials, 0);
        
        if (DrawCustomButton("渲染背面", commonCull == 1, GUILayout.Height(ButtonHeight)))
            SetCullMode(materials, 1);
        
        if (DrawCustomButton("渲染正面", commonCull == 2, GUILayout.Height(ButtonHeight)))
            SetCullMode(materials, 2);
        
        GUILayout.EndHorizontal();
    }

    // 批量设置剔除模式 - 修复版本
    private static void SetCullMode(Material[] materials, int cullMode)
    {
        foreach (var mat in materials)
        {
            Undo.RecordObject(mat, "Change Cull Mode");
            
            // 同时设置所有相关的剔除属性
            mat.SetInt("_Cull", cullMode);
            mat.SetInt("_CullMode", cullMode);
            mat.SetInt("_CullModeForward", cullMode);
            
            // 对于双面渲染，设置额外的GI属性
            if (cullMode == 0)
            {
                if (mat.HasProperty("_DoubleSidedGI"))
                    mat.SetInt("_DoubleSidedGI", 1);
            }
            else
            {
                // 非双面模式时重置双面GI属性（如果存在）
                if (mat.HasProperty("_DoubleSidedGI"))
                    mat.SetInt("_DoubleSidedGI", 0);
            }
            
            EditorUtility.SetDirty(mat);
        }
    }

    // 深度写入控制
    private static void DrawZWriteControls(Material[] materials)
    {
        GUILayout.BeginHorizontal();
        
        int? commonZWrite = null;
        foreach (var mat in materials)
        {
            int zWrite = mat.GetInt("_ZWriteControl");
            if (commonZWrite == null) 
                commonZWrite = zWrite;
            else if (commonZWrite != zWrite) 
            { 
                commonZWrite = -1; 
                break; 
            }
        }

        if (DrawCustomButton("自动深度", commonZWrite == 0, GUILayout.Height(ButtonHeight)))
            SetZWriteMode(materials, 0, 0);
        
        if (DrawCustomButton("开启深度", commonZWrite == 1, GUILayout.Height(ButtonHeight)))
            SetZWriteMode(materials, 1, 1);
        
        if (DrawCustomButton("关闭深度", commonZWrite == 2, GUILayout.Height(ButtonHeight)))
            SetZWriteMode(materials, 0, 2);
        
        GUILayout.EndHorizontal();
    }

    // 批量设置深度写入模式
    private static void SetZWriteMode(Material[] materials, int zWrite, int zWriteControl)
    {
        foreach (var mat in materials)
        {
            Undo.RecordObject(mat, "Change ZWrite Mode");
            mat.SetInt("_ZWrite", zWrite);
            mat.SetInt("_ZWriteControl", zWriteControl);
            EditorUtility.SetDirty(mat);
        }
    }

    // 渲染队列控制
    private static void DrawRenderQueueControl(Material[] materials)
    {
        int? commonQueue = null;
        foreach (var mat in materials)
        {
            int queue = mat.HasProperty("_CustomRenderQueue") ? mat.GetInt("_CustomRenderQueue") : 3000;
            if (commonQueue == null) 
                commonQueue = queue;
            else if (commonQueue != queue) 
            { 
                commonQueue = -1; 
                break; 
            }
        }

        GUILayout.BeginHorizontal();
        int newQueue = EditorGUILayout.IntField(commonQueue ?? 3000, GUILayout.Height(ButtonHeight));
        
        if (newQueue != (commonQueue ?? 3000))
        {
            foreach (var mat in materials)
            {
                Undo.RecordObject(mat, "Change Render Queue");
                mat.SetInt("_CustomRenderQueue", newQueue);
                mat.renderQueue = newQueue;
                EditorUtility.SetDirty(mat);
            }
        }
        GUILayout.EndHorizontal();
    }

    // 实例化和GI控制
    private static void DrawInstancingAndGIControls(Material[] materials)
    {
        GUILayout.BeginHorizontal();
        
        bool? isInstancingEnabled = null;
        foreach (var mat in materials)
        {
            bool enabled = mat.enableInstancing;
            if (isInstancingEnabled == null) 
                isInstancingEnabled = enabled;
            else if (isInstancingEnabled != enabled) 
            { 
                isInstancingEnabled = null; 
                break; 
            }
        }

        if (DrawCustomButton("关闭实例化", isInstancingEnabled.HasValue && !isInstancingEnabled.Value, GUILayout.Height(ButtonHeight)))
            SetInstancing(materials, 0);
        
        if (DrawCustomButton("开启实例化", isInstancingEnabled.HasValue && isInstancingEnabled.Value, GUILayout.Height(ButtonHeight)))
            SetInstancing(materials, 1);
        
        GUILayout.EndHorizontal();
    }

    // 批量设置实例化
    private static void SetInstancing(Material[] materials, int enable)
    {
        foreach (var mat in materials)
        {
            Undo.RecordObject(mat, "Change Instancing");
            mat.SetInt("_EnableInstancingVariants", enable);
            mat.enableInstancing = enable == 1;
            EditorUtility.SetDirty(mat);
        }
    }
}